package com.opgea.crm.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.opgea.crm.common.constant.ApplicationConstant;
import com.opgea.crm.domain.entities.Employee;

@Repository
public class EmployeeRepoImpl implements EmployeeRepo{

	@PersistenceContext
	EntityManager em;
	
	@Transactional
	public void create(Employee employee) {
		em.persist(employee);
	}

	@Transactional(propagation=Propagation.REQUIRED)
	public void remove(long id) {
       Employee employee = em.find(Employee.class, id);
		em.remove(employee);
	}
	
	//@Transactional(propagation=Propagation.REQUIRED)
	@Transactional
	public void update(Employee employee) {
		if (em.find(Employee.class, employee.getId()) == null) {
	        throw new IllegalArgumentException("Unknown employee id: " + employee.getId());
	      }
		Employee managedEmployee = em.merge(employee);	
	}	

	@Override
	public Employee find(long id) {
		return em.find(Employee.class, id);
	}

	
	
	@Override
	public List<Employee> findUserList(String criteria, String value) {
		StringBuffer buffer=new StringBuffer("SELECT e FROM Employee e");
		String cond=" WHERE ";
		
		System.out.println("Criteria : "+criteria);
		
		if( (Integer.valueOf(criteria) == ApplicationConstant.UserSearchCriteriaQualifier.FirstName.ordinal())
				){
			buffer.append(cond);
			buffer.append(" e.firstName like :paramVal");
			
			}
		
		if((Integer.valueOf(criteria) == ApplicationConstant.UserSearchCriteriaQualifier.LastName.ordinal())
				){
			buffer.append(cond);
			buffer.append(" e.lastName like :paramVal");
			
		}
		
		Query query=em.createQuery(buffer.toString());
		query.setParameter("paramVal", value+'%');
		
		return (List<Employee>)query.getResultList();
	}

	@Override
	public List<Employee> findAll() {
		String queryStr = "SELECT e FROM Employee e";
		Query query = em.createQuery(queryStr); 
		List<Employee> empList = query.getResultList();
		return empList;
	}

	@Override
	public List<Employee> findByCompanyId(long companyId) {
		String query = "SELECT e FROM Employee e WHERE e.company.id = "+companyId;
		return em.createQuery(query, Employee.class).getResultList();
	}

	@Override
	public List<Employee> findByLeadId() {
		String query = "SELECT l.leadprofile.employee FROM Lead l";
		return em.createQuery(query,Employee.class).getResultList();
	}
	
	
}
